<?php
namespace Admin\Controller;
use Common\Controller\AdminBaseController;
/**
 * 后台首页控制器
 */
class MemberController extends AdminBaseController{
	/**
	 * 首页
	 */
	public function index(){
		if($_GET['status']){
	     $condition['status']= $_GET['status'];
	    }
	    if($_GET['is_agent']){
	     $condition['is_agent']= $_GET['is_agent'];
	    }
	    if($_GET['member_rank']){
	     $condition['member_rank']= $_GET['member_rank'];
	    }
	    if($_GET['sex']){
	     $condition['sex']= $_GET['sex'];
	    }
	    if($_GET['member_name']){
	      if(preg_match("/^1[34578]{1}\d{9}$/",$phonenumber)){  
	      	$condition['member_mobile']= $_GET['member_name'];
	      }else{
	      	$condition['member_name']= $_GET['member_name'];
	      }	
	     
	    }
	    if($_GET['strtime'] || $_GET['endtime']){
	     $condition['strtime']= $_GET['strtime'];
	     $condition['endtime']= $_GET['endtime'];
	    }
		 
	    $data=D('Member')->getMemberList($condition,'20');
	   
	    if (is_array($data['data'])){
			foreach ($data['data'] as $k=> $v){
 				$data['data'][$k]['member_rank_name'] =M('member_rank')->where('rank_id='.$v['member_rank'])->getField('rank_name');
 				$data['data'][$k]['parent_name'] =M('member')->where('parent_id='.$v['member_id'])->getField('member_name');
 				$data['data'][$k]['num'] =M('member')->where('parent_id='.$v['member_id'])->count();
			}
		}
		$rank=M('member_rank')->select();
		$this->assign('member',$data);
		$this->assign('rank',$rank);
		$this->display();
	}

	/**
	 * 新增会员
	 */
	public function member_add(){
		$model_member=D('member');
		if(IS_POST){
			$insert_array = array();
			$insert_array['member_name'] = trim($_POST['member_name']);
			$insert_array['true_name'] = trim($_POST['true_name']);
			$insert_array['birthday'] = strtotime(trim($_POST['birthday']));
			$insert_array['sex'] = intval($_POST['sex']);
			$insert_array['member_email'] = trim($_POST['member_email']);
			$insert_array['member_mobile'] = trim($_POST['member_mobile']);
			$insert_array['qq'] = trim($_POST['qq']);
			$insert_array['wechat'] = trim($_POST['wechat']);
			$insert_array['bank_name'] = trim($_POST['bank_name']);
			$insert_array['bank_user'] = trim($_POST['bank_user']);
			$insert_array['bank_num'] = trim($_POST['bank_num']);
			$insert_array['member_password'] = MD5(trim($_POST['password']));
			if(intval($_POST['member_rank'])==0){
			$insert_array['member_rank'] = 1;	
				}else{
			$insert_array['member_rank'] = intval($_POST['member_rank']);
				}
			$insert_array['status'] = intval($_POST['status']);
			$insert_array['is_agent'] = intval($_POST['is_agent']);
			$insert_array['parent_id'] = intval($_POST['parent_id']);
			$insert_array['add_time'] = time();
			if($_FILES['member_avatar']['error']==0){
					$m_member = M('member')->max('member_id');
					$member_id=$m_member+1;
					$config=array(
			         'rootPath' => './data/upload/avatar/',
			         'savePath' => '',
 			         'maxSize' => 512000,//500K
			        // 'saveName'   =>    array('date','Ym'),
					 'saveName'   =>    'avatar_'.intval($member_id),
			         'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
			         'autoSub'    =>    false
			        );
			        $upload = new \Think\Upload($config);// 实例化上传类
					// 上传单个文件 
					$info   =   $upload->uploadOne($_FILES['member_avatar']);
					
						if(!$info) {// 上传错误提示错误信息
							$this->error($upload->getError());
						}else{// 上传成功 获取上传文件信息
							 $insert_array['member_avatar'] = $info['savepath'].$info['savename'];
						}
					}
			     $result = $model_member->add($insert_array); 
				if ($result){
 				 	admin_log('添加会员'.'ID:'.$result.'['.$_POST['member_name'].']',1);
					$this->success('添加会员成功','index');exit;
				}else {
					$this->error('添加会员失败','index');exit;
				}  	
		//	print_r($insert_array);exit;
		}
		$rank=M('member_rank')->select();
		$this->assign('rank',$rank);
		$this->display();
	}

	/**
	 * 编辑会员
	 */
	public function member_edit(){
		$id=$_GET['id'];
		$model_member = D('Member');

        if(IS_POST){
			$update_array = array();
			$update_array['member_id'] = trim($_POST['member_id']);
			$update_array['member_name'] = trim($_POST['member_name']);
			$update_array['true_name'] = trim($_POST['true_name']);
			$update_array['birthday'] = strtotime(trim($_POST['birthday']));
			$update_array['sex'] = intval($_POST['sex']);
			$update_array['member_email'] = trim($_POST['member_email']);
			$update_array['member_mobile'] = trim($_POST['member_mobile']);
			$update_array['qq'] = trim($_POST['qq']);
			$update_array['wechat'] = trim($_POST['wechat']);
			$update_array['bank_name'] = trim($_POST['bank_name']);
			$update_array['bank_user'] = trim($_POST['bank_user']);
			$update_array['bank_num'] = trim($_POST['bank_num']);
 			$update_array['member_rank'] = intval($_POST['member_rank']);
			$update_array['status'] = intval($_POST['status']);
			$update_array['is_agent'] = intval($_POST['is_agent']);
			//$update_array['parent_id'] = intval($_POST['parent_id']);
			$update_array['add_time'] = time();
			if(!empty($_POST['password'])){
			$update_array['member_password'] = MD5(trim($_POST['password']));	
				}
			if($_FILES['member_avatar']['error']==0){
					 $member_array = $model_member->getOneMember(intval($_POST['member_id']));
					if(!empty($member_array['member_avatar'])){
					          unlink('./data/upload/avatar/'.$member_array['member_avatar']);
					        }
					$config=array(
			         'rootPath' => './data/upload/avatar/',
			         'savePath' => '',
 			         'maxSize' => 512000,//500K
			        // 'saveName'   =>    array('date','Ym'),
					 'saveName'   =>    'avatar_'.intval($_POST['member_id']),
			         'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
			         'autoSub'    =>    false
			        );
			        $upload = new \Think\Upload($config);// 实例化上传类
					// 上传单个文件 
					$info   =   $upload->uploadOne($_FILES['member_avatar']);
					
						if(!$info) {// 上传错误提示错误信息
							$this->error($upload->getError());
						}else{// 上传成功 获取上传文件信息
							 $update_array['member_avatar'] = $info['savepath'].$info['savename'];
						}
					}
			     $result = $model_member->update($update_array); 
				if ($result){
 				 	admin_log('编辑会员'.'ID:'.$_POST['member_id'].'['.$_POST['member_name'].']',1);
					$this->success('编辑会员成功','index');exit;
				}else {
					$this->error('编辑会员失败','index');exit;
				}  
		}

		$member_array = $model_member->getOneMember(intval($id)); 
		//print_r($member_array);exit;
		$rank=M('member_rank')->select();
		$this->assign('rank',$rank);
		$this->assign('member',$member_array);
		$this->display();
	}
    
    public function ajax(){

    	switch ($_GET['branch']){
			/**
			 * 验证手机号是否重复
			 */
			case 'check_mobile':			
			     
				$model_member = M('member');
				$condition['member_mobile']	= $_GET['member_mobile'];
				 if($_GET['member_id'])
				 {
                  $condition['member_id']	=array('neq',$_GET['member_id']);
				 } 
				$list=$model_member->where($condition)->select(); 
				 
				if (empty($list)){
					echo 'true';exit;
				}else {
					echo 'false';exit;
				}
				break;
			/**
			 * 验证会员是否重复
			 */
			case 'check_name':			
			     
				$model_member = M('member');
				$condition['member_name']	= $_GET['member_name'];
				 if($_GET['member_id'])
				 {
                  $condition['member_id']	=array('neq',$_GET['member_id']);
				 } 
				$list=$model_member->where($condition)->select(); 
				 
				if (empty($list)){
					echo 'true';exit;
				}else {
					echo 'false';exit;
				}
				break;
			/**
			 * 验证会员是否重复
			 */
			case 'get_parent':			
			     
				$data=array('info'=>'获取信息失败','status'=>'0');
				if (!isAJAX) {
		               halt('请求有误');
		         } else{
		        $condition['is_agent']	= '1'; 	
		        if($_GET['member_id'])
				 {
                  $condition['member_id']	=array('neq',$_GET['member_id']);
				 }
				$member=M('member')->where($condition)->select();
				$data=array('info'=>'获取信息成功','status'=>'1','member'=>$member);	
		 		 
				$this->ajaxReturn($data,'json');
				}
				break;	
			 
				
		}
    }

	//修改发布下架状态
	public function member_show(){
		$model_member = D('Member');
		
		if($_POST['id']){
			$update_array['member_id'] = $_POST['id'];
			$update_array['status'] = '1';
			
			}
		if($_POST['member_id']){
		$update_array['status'] = '0';
		$update_array['member_id'] = $_POST['member_id'];
		}
		$info   = $model_member->update($update_array);
		if($info){
			admin_log('修改会员状态ID['.$update_array['member_id'].']',1);
			$data=array('info'=>'修改成功','status'=>'1');
			echo  json_encode($data);exit;
			} else{
			$data=array('info'=>'修改失败','status'=>'0');
			echo  json_encode($data);exit;	
				}
			
	}


	/**
	 * ajax操作
	 */
	public function member_del(){
		$model_member = D('Member');
		 
	    $data=array('info'=>'删除失败','status'=>'0');
	     
	    if (!isAJAX) {
           halt('请求有误');
        } else{
		$id = $_POST['member_id'];
		if (!empty($id)){
 		    $member_array = $model_member->getOneMember(intval($id));
 		    //unlink('./data/upload/avatar/'.$member_array['avatar']);
 		    if(!empty($member_array['avatar'])){
				unlink('./data/upload/avatar/'.$member_array['avatar']);
			}
		    $info = $model_member->del($id);
			if($info){
				 admin_log('删除会员'.'['.$id.']'.$member_array['member_name'],1);
				 $data=array('info'=>'删除成功','status'=>'1');
			}else{
			$data=array('info'=>'删除失败','status'=>'0');	
				}
		} else{
		 $data=array('info'=>'参数有误');	
			}
		 
		$this->ajaxReturn($data,'json');
		}
	}
	//批量删除会员

	public function detadel(){
		$model_member = D('Member');
		
		$member_id = $_POST['member_id'];
		 
		foreach($member_id as $key=>$val){
			$member_array = $model_member->getOneMember(intval($val));
			if(!empty($member_array['avatar'])){
				unlink('./data/upload/avatar/'.$member_array['avatar']);
			}
			$info = $model_member->del($val);
			admin_log('批量删除会员'.'ID['.$val.']'.$member_array['member_name'],1);
			}
		if($info){
			$this->success('删除完成','index');exit;
		}else{
			$this->error('删除失败','index');exit;
			}
		
	}


	public function rank(){
		 
		 
	    $data=D('Member')->getMemberRankList('20');
	    //print_r($data);exit;
		$this->assign('rank',$data);
		$this->display();
	}

/**
	 * 新增会员等级
	 */
	public function rank_add(){
			$data=I('post.');
		    $result=D('Member')->rank_add($data);
		    if ($result) {
			  $this->success('添加成功',U('Admin/Member/rank'));
		    }else{
			  $this->error('添加失败');
		    }
		 
	}
	/**
	 * 修改等级
	 */
	public function rank_edit(){
		$data=I('post.');
		$map=array(
			'rank_id'=>$data['rank_id']
			);
		$result=M('member_rank')->where($map)->save($data);
		if ($result>=0) {
			$this->success('修改成功',U('Admin/Member/rank'));
		}else{
			$this->error('修改失败');
		}
	}
	/**
	 * ajax操作
	 */
	public function rank_del(){
		$model_member = D('Member');
		 
	    $data=array('info'=>'删除失败','status'=>'0');
	     
	    if (!isAJAX) {
           halt('请求有误');
        } else{
		$id = $_POST['rank_id'];
		if (!empty($id)){
		    $info = $model_member->rank_del($id);
			if($info){
				 admin_log('删除会员等级'.'['.$id.']',1);
				 $data=array('info'=>'删除成功','status'=>'1');
			}else{
			$data=array('info'=>'删除失败','status'=>'0');	
			}
		} else{
		 $data=array('info'=>'参数有误');	
		}
		 
		$this->ajaxReturn($data,'json');
		}
	}
	//批量删除会员等级

	public function rankdel(){
		$model_member = D('Member');
		
		$rank_id = $_POST['rank_id'];
		//print_r($rank_id);exit;
		foreach($rank_id as $key=>$val){
			$info = $model_member->rank_del($val);
			//$info = $model_member->del($val);
			admin_log('批量删除会员'.'ID['.$val.']',1);
			}
		if($info){
			$this->success('删除完成','rank');exit;
		}else{
			$this->error('删除失败','rank');exit;
			}
		
	}
	 /**
	 * 修改金额
	 */
	 public function change_money(){
		 
		 if($_POST){
			 $data=I('post.'); 
			
			if($data['money_type']==1){
				//0余额,1冻结资金
				$money_type='member_f_money';
				$title='对用户ID'.$data['member_id'].'的冻结金额增加了'.$data['m_value'].',';
				$map['change_f_money']=$data['m_value'];
			}else{
				$money_type='member_money';
				$title='对用户ID'.$data['member_id'].'的余额增加了'.$data['m_value'].',';
				$map['change_money']=$data['m_value'];
			}
			if($data['type']==1){
				//0增加 ,1减少
					 $result=M('member')->where('member_id='.$data['member_id'])->setDec($money_type,$data['m_value']);
			}else{
					 $result=M('member')->where('member_id='.$data['member_id'])->setInc($money_type,$data['m_value']);
			}
		
		if ($result>0) {
			//变动记录
			$map['m_id']=$data['member_id'];
			
			$map['change_type']=5;
			$map['add_time']=time();
			$map['remark']=$data['about'];
			$map['a_id']=session('ADMIN_ID');
			M('account_log')->add($map);
			admin_log($title);
			$this->success($title.'修改成功',U('Admin/Member/index'));exit;
		}else{
			$this->error($title.'修改失败',U('Admin/Member/change_money/id/'.$data['member_id']));exit;
		}
		 }
		 $member_id=$_GET['id'];
		$data=M('member')->field('member_name,member_id,member_money,member_f_money')->where('member_id='.$member_id)->find();
		
		 $this->assign('member',$data);
		 $this->display();
		 
	 }
	/**
	 * 金额变动记录
	 */
	public function account_log(){
		
		$condition_str = '1';
		 if($_GET['member_name']){
	      if(preg_match("/^1[34578]{1}\d{9}$/",$phonenumber)){  
	      
			$condition_str .= " and member_mobile = '". $condition['member_mobile'] ."'";
	      }else{
	 
			$condition_str .= " and member_name like '%". $condition['member_name'] ."%'";
	      }	
	     
	    }
	    if($_GET['strtime'] || $_GET['endtime']){
	   
		 $condition_str .= " and add_time between '".strtotime($condition['strtime'])."' and '".strtotime($condition['endtime'])."'";
	    }
		$count      = M('account_log')->alias('a')->join('__MEMBER__ m on m.member_id=a.m_id','left')->where($condition_str)->count();
		$Page       =new_page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show       = $Page->show();// 分页显示输出
		
		$data=M('account_log')->field('m.member_name,a.*,c.name as change_type')->alias('a')->
		join('__MEMBER__ m on m.member_id=a.m_id','left')->join('__ACCOUNT_CHANGE_TYPE__ c on c.id=a.change_type','left')
		->where($condition_str)->limit($Page->firstRow.','.$Page->listRows)->select();
		 if (is_array($data)){
			foreach ($data as $k=> $v){
			if($v['a_id']>0){
				$data[$k]['handle']=M('admin_users')->where('id='.$v['a_id'])->getField('username');;
			}else{
				$data[$k]['handle']='用户';
			}
			if($v['change_f_money']>0){
				$data[$k]['change_money']=$$v['change_f_money'];
			}
		}
		}
		
		$this->assign('page',$show);// 赋值分页输出
		$this->assign('list',$data);
		$this->display();
	}

	/**
	 * 代理申请记录
	 */
	public function examine(){
	
			$condition_str = '1';
		 if($_GET['member_name']){
	      if(preg_match("/^1[34578]{1}\d{9}$/",$phonenumber)){  
	      
			$condition_str .= " and member_mobile = '". $_GET['member_mobile'] ."'";
	      }else{
	 
			$condition_str .= " and member_name like '%". $_GET['member_name'] ."%'";
	      }	
	     
	    }
		if($_GET['status']){
	     $condition_str .=" and a.status=".$_GET['status'];
	    }
	    if($_GET['strtime'] || $_GET['endtime']){
	   
		 $condition_str .= " and a.add_time between '".strtotime($_GET['strtime'])."' and '".strtotime($_GET['endtime'])."'";
	    }
		$count      = M('examine')->alias('a')->join('__MEMBER__ m on m.member_id=a.m_id','left')->where($condition_str)->count();
		$Page       =new_page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show       = $Page->show();// 分页显示输出
		
		$data=M('examine')->field('m.member_name,a.*')->alias('a')->
		join('__MEMBER__ m on m.member_id=a.m_id','left')->where($condition_str)->limit($Page->firstRow.','.$Page->listRows)->select();
		 if (is_array($data)){
			foreach ($data as $k=> $v){
			
		}
		}
		
		$this->assign('page',$show);// 赋值分页输出
		$this->assign('list',$data);
		$this->display();
	}

	/**
	 * 代理申请审核
	 */
	 public function examine_audit(){
	 	$data=I('post.');
		$map=array(
			'id'=>$data['id']
			);
			if($data['status']==1){
				$title='通过申请，代理员id:';
			}elseif($data['status']==2){
				$title='拒绝申请,代理员id:';
			}
			$data['ex_time']=time();
		$result=M('examine')->where($map)->save($data);
		if ($result>=0) {
			admin_log($title.$data['id'].',');
			$this->success('审核成功',U('Admin/Member/examine'));
		}else{
			$this->error('审核失败');
		}
		exit;
	 }
	/**
	 * 代理申请删除
	 */
	 public function examine_del(){
		 
		 	$data=I('post.');
		$map=array(
			'id'=>$data['id']
			);
		
		$result=M('examine')->where($map)->delete();
		if ($result>=0) {
			admin_log('删除代理申请，代理员id：'.$data['id'].',');
			$this->success('删除成功',U('Admin/Member/examine'));
		}else{
			$this->error('删除失败');
		}
	 }
	/**
	 * 充值提现管理
	 */
	 public function withdrawals(){
		 if($_POST){
			 $id=$_POST['id'];
			 $condition['id']=$id;
			 $data=M('cash_m')->field('m.member_name,m.bank_name,m.bank_num,a.*')->alias('a')->join('__MEMBER__ m on m.member_id=a.m_id','left')->where($condition)->find();
			if($data['status']==1){
				$data['type']='处理完成';
			}else{
				$data['type']='未处理';
			}
			
			$this->ajaxReturn($data,'json');
		 }
		 $condition_str = '1';
		 if($_GET['member_name']){
	      if(preg_match("/^1[34578]{1}\d{9}$/",$phonenumber)){  
	      
			$condition_str .= " and member_mobile = '". $_GET['member_mobile'] ."'";
	      }else{
	 
			$condition_str .= " and member_name like '%". $_GET['member_name'] ."%'";
	      }	
	     
	    }
		if($_GET['status']){
	     $condition_str .=" and a.status=".$_GET['status'];
	    }
		if($_GET['type']){
	     $condition_str .=" and a.type=".$_GET['type'];
	    }
	    if($_GET['strtime'] || $_GET['endtime']){
	   
		 $condition_str .= " and a.add_time between '".strtotime($_GET['strtime'])."' and '".strtotime($_GET['endtime'])."'";
	    }
		$count      = M('cash_m')->alias('a')->join('__MEMBER__ m on m.member_id=a.m_id','left')->where($condition_str)->count();
		$Page       =new_page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show       = $Page->show();// 分页显示输出
		
		$data=M('cash_m')->field('m.member_name,m.true_name,a.*')->alias('a')->
		join('__MEMBER__ m on m.member_id=a.m_id','left')->where($condition_str)->limit($Page->firstRow.','.$Page->listRows)->select();
		 if (is_array($data)){
			foreach ($data as $k=> $v){
			
		}
		}
		
		$this->assign('page',$show);// 赋值分页输出
		$this->assign('list',$data);
	
		$this->display(); 
	 }
	
	/**
	 * 提现、充值处理
	 */
	 public function cash_save(){
		 
			$data=I('post.');
		$map=array(
			'id'=>$data['id']
			);
			if($data['status']==1){
				
			}else{
			$this->success('未处理',U('Admin/Member/withdrawals'));	
			exit; 
			}
			
		$data['sh_time']=time();

		//$user_id=M('Cash_m')->where($map)->geField('m_id');
		$user=M('Cash_m')->field('m_id,money')->where($map)->find();
		$user_id=$user['m_id'];
        $Member=M('Member');
        $map1['member_id']=$user_id;
		$cash =$Member->field('member_money')->where($map1)->find();
		$member_cash['member_id']=$user_id;
		if ($data['type']==2){
		    //提现
		    $member_cash['member_money']= $cash['member_money'] - $user['money'];
		    if ($member_cash['member_money']>=0){

 		        $Member->save($member_cash);
		        
		         //添加余额变动记录
		        $insert_log['m_id']=$_SESSION['member_id'];
		        $insert_log['change_money']=$member_cash['member_money'];
		        $insert_log['change_type']=4;
		        $insert_log['add_time']=time();
		        $insert_log['remark']='提现：金额：'.$member_cash['member_money'];
		        M('Account_log')->add($insert_log);  
		    } else {
		        $this->error('用户余额不足');
		        exit();
		    }
		}else {
		    //充值
		    $member_cash=$cash['member_money']+$user['money'];
		    $Member->save($member_cash);
 		    //添加余额变动记录
		    $insert_log['m_id']=$_SESSION['member_id'];
		    $insert_log['change_money']=$cash['member_money'];
		    $insert_log['change_type']=3;
		    $insert_log['add_time']=time();
		    $insert_log['remark']='充值：金额：'.$cash['member_money'];
		    M('Account_log')->add($insert_log); 
		}
		$result=M('cash_m')->where($map)->save($data);
		if ($result>=0) {
			if($data['type']==2){
				admin_log('通过提现申请，会员id:'.$user_id);
			}else{
				admin_log('通过充值验证，会员id:'.$user_id);
			}
			
			$this->success('处理成功',U('Admin/Member/withdrawals'));
		}else{
			$this->error('处理失败');
		}
		exit; 
	 }
	 
	//用户充值账号管理
	public function cash_list(){
		if($_POST){
			//删除
			$id=$_POST['id'];
			$result=M('payment')->where('id='.$id)->delete();
			if($result>=0){
				admin_log('删除充值账户');
				die(json_decode(array('status'=>1)));
			}else{
				die(json_decode(array('status'=>0,'info'=>'删除失败')));
			}
		}
		$data=M('payment')->select();
		$this->assign('list',$data);
		$this->display(); 
	}
	public function cash_list_edit(){
		if($_POST){
			$id=$_POST['id'];
			
			$data['sort']=$_POST['sort'];
			$data['name']=$_POST['name'];
			$data['code']=$_POST['code'];
			if($id>0){
				$result=M('payment')->where('id='.$id)->save($data);	
			}else{
			$result=M('payment')->add($data);
			}
		
			if ($result>=0) {
			admin_log('编辑充值账户');
			$this->success('编辑成功',U('Admin/Member/cash_list'));exit;
		}else{
			$this->error('编辑失败');exit;
		}
		}
		$id=$_GET['id'];
		$info=M('payment')->where('id='.$id)->find();
		$this->assign('info',$info);
		$this->display(); 
	}
	
	/* 用户充值账号管理end */
	}
